import React, { Component } from 'react'
import ReactDOM from 'react-dom'
import { createRoot } from "react-dom/client"

// 类式组件
/* class Demo extends Component {
  state = {
    count: 0
  }

  myRef = React.createRef()

  add = () => {
    this.setState( state => ({
      count: state.count * 1 + 1
    }))
  }

  unmount = () => {
    // ReactDOM.unmountComponentAtNode(document.getElementById('countBox'))
    // 新版卸载
    const root = createRoot(document.getElementById('root'));
          root.unmount()
  }

  show = () => {
    alert(this.myRef.current.value)
  }

  componentDidMount() {
    this.timer = setInterval(() => {
      this.setState( state => ({count: state.count * 1 + 1}))
    }, 1000)
  }

  componentWillUnmount() {
    clearInterval(this.timer)
  }

  render() {
    return (
      <div id="countBox">
        <input type="text" ref={this.myRef} />
        <h2>当前求和为{this.state.count}</h2>
        <button onClick={this.add}>点我+1</button>
        <button onClick={this.unmount}>卸载组件</button>
        <button onClick={this.show}>展示</button>
      </div>
    )
  }
} */

// 函数式组件
function Demo() {
  // console.log("Demo");    // 1 + n

  // 底层处理 count被缓存到底层
  const [count, setCount] = React.useState(0)

  function add() {
    // setCount(count * 1 + 1)        // 第一种写法
    setCount(count => count * 1 + 1)  // 第二种写法
  }

  // 卸载组件
  function unmount() {
    const root = createRoot(document.getElementById("root"));
          root.unmount()
  }

  React.useEffect(() => {
    const timerId = setInterval(() => {
      setCount(count => count + 1)
    }, 1000)
    console.log("count:" + count)

    return () => clearInterval(timerId)
  }, [])

  const myRef = React.useRef();

  function show() {
    alert(myRef.current.value)
  }

  return (
    <div>
      <input text="text" ref={myRef} />
      <h2>当前求和为{count}</h2>
      <button onClick={add}>点我+1</button>
      <button onClick={unmount}>卸载组件</button>
      <button onClick={show}>展示</button>
    </div>
  )
}

export default Demo
